<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChUserExt;
use Mine\Abstracts\AbstractMapper;
use Mine\Annotation\Transaction;

class ChUserExtMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChUserExt::class;
    }


    #[Transaction]
    public function setGroup(array $uids, int $groupId): bool
    {
        foreach ($uids as $uid){
            $extInfo = ChUserExt::query()->where('uid', $uid)->first();
            if ($extInfo) {
                $needIncrement = false;
                if ($extInfo->group_id !== $groupId) {
                    // 减少之前分组的账号数量
                    $extInfo->group()->decrement('account_num');
                    $needIncrement = true;
                }
                $extInfo->group_id = $groupId;
                $extInfo->save();
                // 增加新的分组的账号数量
                if ($needIncrement && !empty($groupId)) {
                    $extInfo->group()->increment('account_num');
                }
            }
        }
        return true;
    }

}